/**
 * 本地存储操作
 * Created by kedong on 2017/7/26 0026.
 */
(function () {
    var DB = function () {
        this.userId = userId;
        this.ARRAY_PERFIX = "array_";
        this.OBJECT_PERFIX = "object_";
        this.featuresKey = [];
        this.LAST_CENTER = 'lastCenter';
        this.LAST_ZOOM = 'lastZoom';
    };

    DB.prototype.set = function (key, value, withoutUserId) {
        localStorage.setItem(!!withoutUserId ? key : userId + key, value);
    };

    DB.prototype.get = function (key, withoutUserId) {
        return localStorage.getItem(!!withoutUserId ? key : userId + key);
    };

    /**
     * 保存数组
     * @param arrayKey
     * @param array
     */
    DB.prototype.setArray = function (arrayKey, array) {
        if (!isArray(array)) {
            throw "not array."
        }
        // 先删除
        var length = localStorage.length;
        for (var i = length - 1; i >= 0; i--) {
            var key = localStorage.key(i);
            if (key.indexOf(this.userId + this.ARRAY_PERFIX) > -1 && arrayKey == key.split('_')[1]) {
                localStorage.removeItem(key);
            }
        }
        var key;
        // 再添加
        for (var i = array.length - 1; i >= 0; i--) {
            key = this.ARRAY_PERFIX + arrayKey + '_' + i;
            this.set(key, JSON.stringify(array[i]));
            this.featuresKey.push(key);
        }
        if (this.featuresKey.length > 0) {
            this.set('features', JSON.stringify(this.featuresKey));
        }
    };

    /**
     * 获取数组
     * @param arrayKey
     * @returns {Array}
     */
    DB.prototype.getArray = function (arrayKey) {
        var length = localStorage.length;
        var values = [];
        for (var i = length - 1; i >= 0; i--) {
            var key = localStorage.key(i);
            if (key.indexOf(this.userId + this.ARRAY_PERFIX) > -1 && arrayKey == key.split('_')[1]) {
                values.push(JSON.parse(localStorage.getItem(key)));
            }
        }
        return values;
    };
    DB.prototype.removeFeatures = function () {
        var keys = JSON.parse(this.get('features'));
        for (var i = keys.length - 1; i >= 0; i--) {
            localStorage.removeItem(userId + keys[i]);
        }
    };
    DB.prototype.setLastZoom = function (value) {
        this.set(this.LAST_ZOOM, value);
    };
    DB.prototype.getLastZoom = function () {
        return this.get(this.LAST_ZOOM);
    };
    DB.prototype.setLastCenter = function (value) {
        this.set(this.LAST_CENTER, value);
    };
    DB.prototype.getLastCenter = function () {
        return this.get(this.LAST_CENTER);
    };


    window.DB = new DB();
})(undefined);